<!-- 字典 -->
<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="选择分类" prop="category">
          <!-- <el-cascader
            :options="categoryOptions"
            :props="cascaderProps"
            collapse-tags
            collapse-tags-tooltip
            clearable
            style="width: 200px"
          /> -->
          <el-cascader
            style="width: 200px"
            v-model="queryParams.categoryId"
            :options="categoryOptions"
            :props="{
              value: 'id',
              label: 'name',
              children: 'children',
              emitPath: false,
              checkStrictly: true,
            }"
            clearable
            :show-all-levels="false"
          />
        </el-form-item>
        <el-form-item label="上下架状态">
          <el-select
            v-model="queryParams.isShelf"
            placeholder="全部状态"
            clearable
            style="width: 200px"
          >
            <el-option label="上架" value="1" />
            <el-option label="下架" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item label="产品名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="输入产品名称"
            clearable
            @keyup.enter="handleQuery"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="searchFunc">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never">
      <el-button type="success" icon="plus" @click="OpenAddProduct">新增产品</el-button>
      <el-button type="primary" icon="plus" @click="OpenCategoryDialog">管理产品分类</el-button>
    </el-card>
    <div class="p-2 bg-white flex-1 flex flex-col">
      <base-page-table
        :table-data="tableData"
        :table-columns-data="tableColumnsData"
        :loading="loading"
        :page-num="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :total="queryParams.total"
        max-height="600"
        @handleQuery="handleQuery"
        :table-props="{
          rowKey: 'id',
        }"
      >
        <template #ext="{ row }">
          <div v-if="'ext' in row">
            <el-tag v-for="one in row.ext" :key="one.propertyId" class="mr-1">
              {{ one.tags }}
            </el-tag>
          </div>
          <div v-else>----</div>
        </template>
        <template #isShelf="{ row }">
          <el-switch
            v-model="row.isShelf"
            :active-value="1"
            :inactive-value="0"
            :loading="row.loading"
            v-if="row.isParent"
            :before-change="() => handleShelf(row)"
          />
        </template>
        <template #operation="{ row }">
          <el-button
            type="primary"
            link
            size="small"
            icon="edit"
            @click.stop="handleEdit(row)"
            v-if="row.isParent"
          >
            编辑
          </el-button>
          <el-button
            v-if="row.isParent"
            type="danger"
            link
            size="small"
            icon="delete"
            @click.stop="handleDelete(row.id)"
          >
            删除
          </el-button>
        </template>
      </base-page-table>
    </div>
  </div>
  <AddCategory
    v-model:visible="dialogVisible"
    :table-data="categoryOptions"
    @updateTableData="handleUpdateTableData"
  />
</template>

<script setup>
import AddCategory from "./AddCategory.vue";
import EquityMallAPI from "@/api/equitymall";
import router from "@/router";
const queryFormRef = ref();
const dialogVisible = ref(false);
const loading = ref(false);
const tableColumnsData = ref([
  { prop: "name", label: "产品名称", align: "center" },
  { prop: "categoryName", label: "所属分类", align: "center" },
  { prop: "price", label: "商品价格（￥）", align: "center" },
  { prop: "pointsPrice", label: "积分价格", align: "center" },
  { prop: "isShelf", label: "上下架状态", align: "center", customSlot: "isShelf" },
  {
    prop: "operation",
    label: "操作",
    align: "center",
    customSlot: "operation",
    fixed: "right",
  },
]);
const queryParams = reactive({
  categoryId: "",
  isShelf: "",
  name: "",
  pageNum: 1,
  pageSize: 20,
  total: 0,
});

const tableData = ref([]);

// 查询
function handleQuery(val) {
  queryParams.pageNum = val.pageNum;
  queryParams.pageSize = val.pageSize;
  getProductList();
}
function searchFunc() {
  queryParams.pageNum = 1;
  getProductList();
}
// 重置查询
function handleResetQuery() {
  queryParams.categoryId = "";
  queryParams.isShelf = "";
  queryParams.name = "";
  queryParams.pageNum = 1;
  queryParams.pageSize = 20;
  searchFunc();
}

function OpenCategoryDialog() {
  dialogVisible.value = true;
}
const categoryOptions = ref([]);
const categoryPageQuery = reactive({
  pageNum: 1,
  pageSize: 20,
});
// 更新产品分类
const handleUpdateTableData = () => {
  getProductCategoryPage();
};
// 分页查询产品分类
const getProductCategoryPage = async () => {
  try {
    const res = await EquityMallAPI.getProductCategoryPage(categoryPageQuery);
    categoryOptions.value = buildTree(res.list);
  } catch (error) {
    console.error(error);
  }
};
// 处理数据
function buildTree(nodes) {
  // 创建一个映射表，用于快速查找父节点
  const nodeMap = {};
  nodes.forEach((node) => {
    nodeMap[node.id] = { ...node, children: [] }; // 添加 children 属性
  });

  // 构建树形结构
  const tree = [];
  nodes.forEach((node) => {
    if (node.parentId === null) {
      // 如果 parentId 为 null，则为根节点
      tree.push(nodeMap[node.id]);
    } else {
      // 如果有 parentId，则找到对应的父节点并添加到 children 中
      const parent = nodeMap[node.parentId];
      if (parent) {
        parent.children.push(nodeMap[node.id]);
      }
    }
  });
  return tree;
}
/**
 * 获取商品列表
 */
const getProductList = async () => {
  try {
    loading.value = true;
    const res = await EquityMallAPI.getProductPage({
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      categoryId: queryParams.categoryId,
      isShelf: queryParams.isShelf,
      name: queryParams.name,
    });
    tableData.value = res.list.map((item) => {
      let one = {
        isParent: true,
        ...item,
      };
      // 只有一个并且ext为空，说明没有属性
      if (item?.prices?.length === 1 && !item?.prices?.[0]?.ext?.length) {
        one.price = item.prices[0].price;
        one.pointsPrice = item.prices[0].pointsPrice;
        return one;
      }
      // 多个肯定是有属性了
      if (item?.prices?.[0]?.ext?.length) {
        one.price = "---";
        one.pointsPrice = "---";
        one.children = item.prices.map((price, index) => {
          return {
            name: `${item.name} - (${price.ext.map((one) => one.tags).join("*")})`,
            ...price,
            categoryName: item.categoryName,
            id: `ext-${index}`,
            isParent: false,
          };
        });
      }
      return one;
    });
    queryParams.total = res.total;
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};
// 打开新增商品
function OpenAddProduct() {
  router.push({
    path: "/equitymall/add-product",
  });
}
// 编辑
function handleEdit(row) {
  router.push({
    path: "/equitymall/edit-product",
    query: { id: row.id },
  });
}
// 删除
function handleDelete(id) {
  ElMessageBox.confirm("确定删除该商品吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await EquityMallAPI.deleteProductByIds({ ids: [id] });
    ElMessage.success("删除成功");
    getProductList();
  });
}
// 上架
async function handleShelf(row) {
  row.loading = true;
  //et(row, "loading", true);
  try {
    await EquityMallAPI.shelfProduct({ id: row.id, isShelf: row.isShelf === 1 ? 0 : 1 });
    ElMessage.success(row.isShelf === 1 ? "下架成功" : "上架成功");
    row.loading = false;
    getProductList();
    return true;
  } catch (error) {
    console.error(error);
    row.loading = false;
    return false;
  }
  // ElMessageBox.confirm("确定上架该商品吗？", "提示", {
  //   confirmButtonText: "确定",
  //   cancelButtonText: "取消",
  //   type: "warning",
  // }).then(async () => {

  // });
}
onMounted(() => {
  getProductCategoryPage();
  getProductList();
});
</script>
